/*
 * Duplicate Detector Copyright (C) 2010 Marco Biscaro <marcobiscaro2112@gmail.com>
 * 
 * This file is part of Duplicate Detector.
 *
 * Duplicate Detector is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Duplicate Detector is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Duplicate Detector.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.duplicatedetector.model;

import java.util.HashSet;
import java.util.Set;

import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 * Simple class to handle {@link TreeModelListener}'s and fire
 * {@link TreeModelEvent}'s.
 * 
 * @author Marco Biscaro
 */
public abstract class AbstractTreeModel implements TreeModel {

	protected Set<TreeModelListener> listeners = new HashSet<TreeModelListener>();

	@Override
	public void addTreeModelListener(TreeModelListener l) {
		listeners.add(l);
	}

	@Override
	public void removeTreeModelListener(TreeModelListener l) {
		listeners.remove(l);
	}

	@Override
	public void valueForPathChanged(TreePath path, Object newValue) {
		// do nothing
	}

	public TreeModelListener[] getTreeModelListeners() {
		return listeners.toArray(new TreeModelListener[listeners.size()]);
	}

	protected void fireTreeNodesChanged(Object source, Object[] path,
			int[] childIndices, Object[] children) {
		TreeModelEvent e = new TreeModelEvent(source, path, childIndices,
				children);
		for (TreeModelListener listener : listeners) {
			listener.treeNodesChanged(e);
		}
	}

	protected void fireTreeNodesInserted(Object source, Object[] path,
			int[] childIndices, Object[] children) {
		TreeModelEvent e = new TreeModelEvent(source, path, childIndices,
				children);
		for (TreeModelListener listener : listeners) {
			listener.treeNodesInserted(e);
		}
	}

	protected void fireTreeNodesRemoved(Object source, Object[] path,
			int[] childIndices, Object[] children) {
		TreeModelEvent e = new TreeModelEvent(source, path, childIndices,
				children);
		for (TreeModelListener listener : listeners) {
			listener.treeNodesRemoved(e);
		}
	}

	protected void fireTreeStructureChanged() {
		TreeModelEvent e = new TreeModelEvent(this, new TreePath(getRoot()));
		for (TreeModelListener listener : listeners) {
			listener.treeStructureChanged(e);
		}
	}

}
